local mlfs = require("common.libLfs")

local _F = {}

_F._VERSION = '0.01'

local mt = { __index = _F }

-- 检查是否文件夹,并尝试创建
function _F.checkSaveDir(p)
    if not mlfs.isDir(p) then
        ngx.log(ngx.DEBUG, "Not such file or directory : ", p)
        if not mlfs.createDir(p) then
            ngx.log(ngx.WARN, "Create new path failed : ", p)
            return false
        end
        ngx.log(ngx.DEBUG, "Create new path succeed : ", p)
    end
    ngx.log(ngx.DEBUG, "Directory already exists : ", p)
    return true
end

-- 检查文件或目录是否存在
function _F.checkLocalFileMD5(f)
    local local_file_md5 = ''
    local local_md5_file = f .. '.md5'
    if mlfs.exFile(f) then
        if mlfs.exFile(local_md5_file) then
            ngx.log(ngx.DEBUG, "Read MD5 file : ", local_md5_file)
            local read_f = io.input(local_md5_file)
            while true do
                line = io.read()      --逐行读取内容，文件结束时返回nil
                if nil == line then
                    break
                elseif nil ~= string.find(line,"MD5:") then
                    local_file_md5 = string.gsub(line, 'MD5:', '')
                    ngx.log(ngx.DEBUG, "Read local file's MD5 value is : ", local_file_md5)
                    break
                end
            end
            read_f:close()
        else
            ngx.log(ngx.DEBUG, "Output file encryption string MD5 : ", f)
            local read_f = io.open(f,"rb")
            local_file_md5 = ngx.md5(read_f:read("*a"))
            ngx.log(ngx.DEBUG, "Output local file's MD5 value is : ", local_file_md5)
            read_f:close()
        end
    end
    return local_file_md5
end

function _F.saveDelFile(f)
    if mlfs.exFile(f) then
        ngx.log(ngx.DEBUG, "Delete source file : ", f)
        os.remove(f)
    end
end

return _F
